﻿//---------------------------------------------------------------
// <copyright company="CounterSoft Limited">
//     Copyright (c) CounterSoft Limited. All rights reserved.
// </copyright> 
//---------------------------------------------------------------
using System;
using System.IO;
using System.Windows.Forms;
using CounterSoft.Gemini.WebServices;
using CounterSoft.Gemini.Commons;
using CounterSoft.Gemini.Commons.Entity;
using CounterSoft.Gemini.Logging;

namespace CounterSoft.Gemini.SnagIt
{
    public partial class SnagItForm : Form
    {
        #region Variables

        private ServiceManager serviceManager;

        #endregion

        #region Properties

        #endregion

        #region Lifecycle

        public SnagItForm()
        {
            InitializeComponent();
        }

        public SnagItForm(string[] args)
        {
            InitializeComponent();
            Configure(args);
        }

        #endregion

        #region Events

        private void btnCapture_Click(object sender, EventArgs e)
        {
            try
            {
                serviceManager = new ServiceManager(txtURL.Text, txtUsername.Text, "", txtAPIKey.Text, chkWinAuth.Checked);
                UserEN user;
                IssueEN issue;
                int issueId = 0;
                string filename = txtFilename.Text.Trim();
                GeminiConfigurationEN config;

                user = serviceManager.UsersService.WhoAmI();
                config = serviceManager.AdminService.GetConfiguration();

                try
                {
                    issueId = Int32.Parse(txtIssueID.Text);
                }
                catch
                {
                }

                if (issueId == 0)
                {
                    MessageBox.Show("Invalid Issue ID.",
                                    "CounterSoft Gemini Snagit Capture",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);

                    return;
                }

                issue = serviceManager.IssuesService.GetIssue(issueId);

                if (issue.IssueID < 1)
                {
                    MessageBox.Show("No issue found.",
                                    "CounterSoft Gemini Snagit Capture",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);

                    return;
                }

                IssueCommentEN comment = new IssueCommentEN();
                comment.IssueID = issueId;
                comment.UserID = user.UserID;
                comment.Comment = txtComment.Text;
                comment.ProjectID = issue.ProjectID;

                FileEN file = new FileEN();

                FileStream fs = File.OpenRead(filename);
                byte[] fileContent = new byte[fs.Length];
                long len = fs.Read(fileContent, 0, fileContent.Length);

                file.IssueID = issueId;
                file.ContentLength = (int)len;
                file.ContentType = GetContentType(filename);
                file.FileData = fileContent;
                file.ProjectID = issue.ProjectID;
                file.FileName = Path.GetFileName(filename);

                comment.Attachment = file;
                comment = serviceManager.IssuesService.CreateComment(issueId, comment);

                if (!config.FullGeminiURL.EndsWith("/")) config.FullGeminiURL += "/";

                string issueURL = String.Format("{0}Default.aspx?p={1}&i={2}",
                    config.FullGeminiURL, issue.ProjectID, issue.IssueID);

                Label lblUrl = new Label();
                lblUrl.Text = issueURL;

                string msg = String.Format("Screen capture attached to issue. {0} {1} {2}",
                    System.Environment.NewLine, System.Environment.NewLine, lblUrl.ToString());

                SuccessForm success = new SuccessForm(issueURL);
                success.ShowDialog();
                success.Close();

                Application.Exit();
            }
            catch (Exception ex)
            {
                string msg = String.Format("Error encountered. {0} {1} {2}",
                    System.Environment.NewLine, System.Environment.NewLine,
                    ex.Message);

                MessageBox.Show(msg, "CounterSoft Gemini Snagit Capture",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);

                DiagnosticsManager.TraceException("Failure", ex);

                return;
            }
        }

        private void SnagItForm_Load(object sender, EventArgs e)
        {
            if (txtUsername.Text.Length > 0)
            {
                txtIssueID.Focus();
            }
        }

        #endregion

        #region Helpers

        private bool Configure(string[] args)
        {
            bool result = false;

            // arg 0 - exe filename
            // arg 1 - screen capture filename
            // arg 2 - Gemini URL
            // arg 3 - Gemini Username
            // arg 4 - Gemini API
            // arg 5 - Gemini Issue ID (not used in Snagit)

            if (args.Length >= 5)
            {
                txtFilename.Text = args[1];
                txtURL.Text = args[2];
                txtUsername.Text = args[3];
                txtAPIKey.Text = args[4];
                //txtIssueID.Text = args[5];

            }

            return result;
        }

        private string GetContentType(string fileName)
        {
            fileName = fileName.Trim().ToUpper();

            if (fileName.EndsWith(".JPG"))
            {
                return "image/jpg";
            }
            else if (fileName.EndsWith(".GIF"))
            {
                return "image/gif";
            }
            else if (fileName.EndsWith(".BMP"))
            {
                return "image/bmp";
            }
            else if (fileName.EndsWith(".TXT"))
            {
                return "text/plain";
            }
            else if (fileName.EndsWith(".DOC"))
            {
                return "application/msword";
            }
            else if (fileName.EndsWith(".XLS"))
            {
                return "application/vnd.ms-excel";
            }
            else if (fileName.EndsWith(".ZIP"))
            {
                return "application/x-zip-compressed";
            }
            else if (fileName.EndsWith(".EXE"))
            {
                return "application/octet-stream";
            }
            else
            {
                return "text/plain";
            }
        }

        #endregion

        private void chkWinAuth_CheckedChanged(object sender, EventArgs e)
        {
            txtUsername.Enabled = !chkWinAuth.Checked;
            txtAPIKey.Enabled = !chkWinAuth.Checked;

            if (txtUsername.Enabled)
            {
                txtUsername.Text = "";
            }
            else
            {
                txtUsername.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            }
        }
    }
}
